package com.freedom.rpc.thrift.client.queue;

import java.util.HashMap;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.freedom.rpc.thrift.client.utils.MyJedisProperties;
import com.freedom.rpc.thrift.common.utils.LoggerUtils;

public class MyHeartbeatQueue {

	// poll: 若队列为空，返回null。
	// remove:若队列为空，抛出NoSuchElementException异常。
	// take:若队列为空，发生阻塞，等待有元素。

	// put---无空间会等待
	// add--- 满时,立即返回,会抛出异常
	// offer---满时,立即返回,不抛异常

	private static final Logger logger = LogManager.getLogger(MyHeartbeatQueue.class);
	private static HashMap<String, BlockingQueue<String>> maps = new HashMap<String, BlockingQueue<String>>();

	static {
		// 获取所有服务的类型
		MyJedisProperties property = MyJedisProperties.getInstance();
		String[] channels = property.getServiceChannels();
		for (String channel : channels) {
			maps.put(channel.trim(), new LinkedBlockingQueue<String>());// 足够大了
		}
	}

	public static void addObject(String channel, String address) {
		try {
			BlockingQueue<String> objectQueue = maps.get(channel);
			if (null != objectQueue) {
				objectQueue.put(address);
			}
		} catch (Exception e) {
			LoggerUtils.error(logger, "fail to put event into operation queue" + e.toString());
		}
	};

	public static String getObject(String channel) {
		try {
			BlockingQueue<String> objectQueue = maps.get(channel);
			return objectQueue.poll();
		} catch (Exception e) {
			return null;
		}
	}

	public static void init() {
		// 仅仅用来触发static里面的内容
	}
}
